package com.hy;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:
 * User:Mr.Du
 * Date:2024/7/4
 * Time:23:56
 */
public class TestCompletableFuture {

    public static void main(String[] args) {
        CompletableFuture future = CompletableFuture.supplyAsync(() -> {
            System.out.println("supplyAsync");
            return 1;
        }).thenApply(i -> {
            System.out.println("thenApply");
            return i + 1;
        }).thenAccept(i -> {
            System.out.println("thenAccept");
            System.out.println(i);
        });
        ExecutorService executorService  = Executors.newFixedThreadPool(10);
        CompletableFuture.supplyAsync( () -> {
            System.out.println(1);
            return 1;
        }, executorService);
        CompletableFuture.runAsync(() ->{
            System.out.println(2);
        }, executorService);


        CompletableFuture<String> task = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务1开始执行，当前时间：" + System.currentTimeMillis());
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务1执行完毕，当前时间：" + System.currentTimeMillis());
            return "task1";
        });

        CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务2开始执行，当前时间：" + System.currentTimeMillis());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务2执行完毕，当前时间：" + System.currentTimeMillis());
            return "task2";
        });

        task.acceptEitherAsync(task2, (res) -> {
            System.out.println("任务3开始执行，当前时间：" + System.currentTimeMillis());
            System.out.println("上一个任务的结果为：" + res);
        });
        

        // 增加一些延迟时间，确保异步任务有足够的时间完成
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
